#include "l7image.h"
#include <QDebug>
#include <QMessageBox>

L7Image::L7Image()
{
}

bool L7Image::readImage(QVector<QString> headers)
{
    QFile file1(headers.at(0));
    QFile file2(headers.at(1)); //por ahora sin uso

    QString data1, data2;

    if (!file1.open(QIODevice::ReadWrite))
        return false;
    else
    {
        QTextStream in(&file1);
        while (!in.atEnd())
        {
            data1 += in.readLine();
        }
    }
    file1.close();

    if (!file2.open(QIODevice::ReadWrite))
        return false;
    else
    {
        QTextStream in(&file2);
        while (!in.atEnd())
        {
            data2 += in.readLine();
        }
    }
    file2.close();

    int index = 0;
    QVariant value;
    QFileInfo inf1(file1);

    // busco el ancho de la imagen
    index = data1.indexOf("PIXELS PER LINE");
    value = this->getNumericValueOf(index + 17, data1);
    this->width = value.toInt();

    // busco el alto de la imagen
    index = data1.indexOf("LINES PER BAND");
    value = this->getNumericValueOf(index + 16, data1);
    this->height = value.toInt();

    // busco los nombres de los archivos de cada banda
    // banda 1
    index = data1.indexOf("FILENAME");
    value = this->getBandName(index + 10, data1);
    this->bandsPaths << inf1.absolutePath() + value.toString();

    // banda 2
    index = data1.indexOf("FILENAME",index + 10);
    value = this->getBandName(index + 10, data1);
    this->bandsPaths << inf1.absolutePath() + value.toString();

    // banda 3
    index = data1.indexOf("FILENAME",index + 10);
    value = this->getBandName(index + 10, data1);
    this->bandsPaths << inf1.absolutePath() + value.toString();

    // banda 4
    index = data1.indexOf("FILENAME",index + 10);
    value = this->getBandName(index + 10, data1);
    this->bandsPaths << inf1.absolutePath() + value.toString();

    // banda 5
    index = data1.indexOf("FILENAME",index + 10);
    value = this->getBandName(index + 10, data1);
    this->bandsPaths << inf1.absolutePath() + value.toString();

    // banda 7
    index = data1.indexOf("FILENAME",index + 10);
    value = this->getBandName(index + 10, data1);
    this->bandsPaths << inf1.absolutePath() + value.toString();

    // banda 6 (por ahora solo leo una de las bandas para compatibilidad con LANSAT 5)
    index = data2.indexOf("FILENAME");
    value = this->getBandName(index + 10, data2);
    this->bandsPaths.insert(5, inf1.absolutePath() + value.toString());

    qDebug() << this->bandsPaths.at(0);
    qDebug() << this->bandsPaths.at(1);
    qDebug() << this->bandsPaths.at(2);
    qDebug() << this->bandsPaths.at(3);
    qDebug() << this->bandsPaths.at(4);
    qDebug() << this->bandsPaths.at(5);
    qDebug() << this->bandsPaths.at(6);

    return true;
}

QString L7Image::getBandName(int beginIndex, QString data)
{
    int endIndex = data.indexOf(".FST", beginIndex);
    QString value = "/" + data.mid(beginIndex,endIndex-beginIndex) + ".FST";

    return value;
}
